package com.googlecode.objectify.impl.translate;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.ShortBlob;
import com.googlecode.objectify.impl.Path;


/**
 * Translates a byte[] to Blob.  Make sure this translator gets registered *before* the normal ArrayTranslator
 * otherwise it won't get used.
 * 
 * @author Jeff Schnitzer <jeff@infohazard.org>
 */
public class ByteArrayTranslatorFactory extends ValueTranslatorFactory<byte[],Object> {

	private static final Logger log = Logger.getLogger(StringTranslatorFactory.class.getName());
	
	/** The pojo type this factory recognizes */
	private static final Class<? extends byte[]> BYTE_ARRAY_TYPE = byte[].class;

	/**
	 */
	protected ByteArrayTranslatorFactory() {
		super(BYTE_ARRAY_TYPE);
	}

	@Override
	protected ValueTranslator<byte[], Object> createValueTranslator(TypeKey<byte[]> tk, CreateContext ctx, Path path) {
		return new ValueTranslator<byte[], Object>(Object.class, byte[].class) { 
			@Override
			protected byte[] loadValue(Object value, LoadContext ctx, Path path) throws SkipException {
				if (value instanceof ShortBlob)
					return ((ShortBlob)value).getBytes();
				else if (value instanceof Blob)
					return ((Blob)value).getBytes();
				else
					return null;
			}

			@Override
			protected Object saveValue(byte[] value, boolean index, SaveContext ctx, Path path) throws SkipException {
				// Check to see if it's short enough to fit in a ShortBlob or needs to be a Blob instead.
				if (value.length > 500) {
					if (index)
						log.log(Level.WARNING, "Attempt to index a byte array which has been automatically converted to an un-indexed Blob. The property is at " + path);

					return new Blob(value);
				} else {
					return new ShortBlob(value);
				}
			}
		};
	}	
	
	
}
